﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Torch_Services
{
    public class FunctionService : IFunctionService
    {
        private IFunctionDal _func;
        private IMapper _mapper;
        public FunctionService(IFunctionDal func, IMapper mapper)
        {
            _func = func;
            _mapper = mapper;
        }

        public async Task<int> AddFunctionAsync(string title, string image, string link)
        {
            return await _func.AddAsync(new Function
            {
                Title = title,
                Image = image,
                Link = link
            });
        }

        public async Task<int> DeleteFunctionAsync(int id)
        {
            var data = await _func.QueryAsync(id);
            return data == null ? -1 : await _func.DeleteAsync(data);
        }

        public async Task<int> EditFunctionAsync(int id, string title, string image, string link)
        {
            var data = await _func.QueryAsync(id);
            if (data == null)
                return -1;
            data.Title = title;
            data.Image = image;
            data.Link = link;
            return await _func.EditAsync(data);
        }

        public async Task<List<FunctionDto>> QueryAllFunctionAsync()
        {
            try
            {
                var data = await _func.QueryAsync();
                return _mapper.Map<List<Function>, List<FunctionDto>>(data);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<FunctionDto> QueryByIdFunctionAsync(int id)
        {
            var data = await _func.QueryAsync(id);
            return _mapper.Map<Function, FunctionDto>(data);
        }

        public async Task<List<FunctionDto>> QueryByTitleFunctionAsync(string title)
        {
            var data = await _func.QueryAsync(f => f.Title.Contains(title));
            return _mapper.Map<List<Function>, List<FunctionDto>>(data);
        }
    }
}
